package redis

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/spf13/viper"
	"time"
)

/**
 * redis数据库连接
 */

var conn redis.Conn
var pool *redis.Pool
var err error

func InitRedis() {

	//建立Redis连接池
	pool = &redis.Pool{
		MaxIdle:     viper.GetInt("redis.maxIdle"),
		MaxActive:   viper.GetInt("redis.maxActive"),
		IdleTimeout: time.Duration(viper.GetInt("redis.idleTimeout")),
		Wait:        viper.GetBool("redis.wait"),
		Dial: func() (redis.Conn, error) {

			network := viper.GetString("redis.network")
			address := viper.GetString("redis.address")
			port := viper.GetString("redis.port")

			return redis.Dial(network, address+":"+port)
		},
	}
	conn = pool.Get()
}

func SetValueByKey(key string, value string) bool {

	_, err1 := conn.Do("SET", key, value)
	if err1 != nil {
		panic(err1)
		return false
	}
	_, err2 := conn.Do("expire", key, 36000)
	if err2 != nil {
		panic(err2)
		return false
	}
	return true
}

func GetValueByKey(key string) (string, string) {
	value, err := redis.String(conn.Do("GET", key))
	if err != nil {
		fmt.Println(err.Error())
		return key, value
	}
	return key, value
}

func SetToken(username string, token string) bool {
	_, err = conn.Do("SET", username, token, "EX", "3600")

	if err != nil {
		fmt.Println("redis:" + err.Error())
		return false
	}
	return true
}

func GetToken(username string) (bool, string) {

	token, err := redis.String(conn.Do("GET", username))
	if err != nil {
		fmt.Println(err.Error())
		return false, token
	}
	return true, token
}
